package org.xs.web.http;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.io.Serializable;
import java.security.SecureRandom;

public class Flash implements Serializable{

	private static final long serialVersionUID = 1L;
	
	private static final String Key = "flash.key";
	private Map<String, String> flashs = new HashMap<String, String>();
	
	private static SecureRandom flashRandom = new SecureRandom();
	private boolean isRead = false;
	
	private Flash(){
		
	}
	
	private void clean(){
		if(isRead)
		if(S.session() != null ){
			S.session().remove(Key);
		}
	}
	private Flash init(){
		if(S.session() != null ){ 
			S.session().set(Key, this);
		}
		return this;
	}
	
	private static boolean hasFlash(){
		if(S.session() != null ){
			return S.session().get(Key) != null;
		}
		return false;
	}
	private static Flash getFlash(){
		return (Flash) S.session().get(Key);
	}
	
	public void flash(String key,String value){
		flashs.put(key, value);
	}
	
	public void flash(String value){
		flashs.put("FLASH_"+flashRandom.nextLong(), value);
	}
	
	public boolean have(){
		return flashs.size() > 0;
	}
	
	public Collection<String> list(){
		return flash().values();
	}
	
	public Map<String, String> flash(){
		isRead = true;
		clean();
		return Collections.unmodifiableMap(flashs);
	}
	
	public static Flash create(){
		 if(hasFlash()){
			 return getFlash();
		 }
		 return new Flash().init();
	}
	
}
